<?php
namespace app\server;

use think\App;
use think\Config;
use think\Request;
use think\swoole\contract\websocket\HandlerInterface;
use Swoole\Server;
use Swoole\Websocket\Frame;
use think\facade\Log;
use think\facade\Cache;

class Handler implements HandlerInterface
{
    
    protected $server;
    protected $config;
    
    public function __construct(App $app)
    {
        $this->server = $app->make(Server::class);
        $this->config = $app->config;
    }
    
    public function onOpen($fd, Request $request){
        return true;
    }
    
    /**
     *
     * @param Frame $frame
     * @return void
     * @author  autumu
     */
    public function onMessage(Frame $frame)
    {
    	$user = empty(Cache::get('user')) ? [] : Cache::get('user');
        $service = empty(Cache::get('service')) ? [] : Cache::get('service');
        $data = json_decode($frame->data, true);
        
        if ($data['data']['from'] == 'user') {
            $user[0] = $frame->fd;
            if (count($service)) {
                $this->server->push($service[0], json_encode([
                    'from' => 'user',
                    'msg_type' => 'text',
                    'msg' => $data['data']['msg']
                ]));
            }
        } elseif ($data['data']['from'] == 'service')  {
            $service[0] = $frame->fd;
            if (count($user)) {
                $this->server->push($user[0], json_encode([
                    'from' => 'service',
                    'msg_type' => 'text',
                    'msg' => $data['data']['msg']
                ]));
            }
        }
        // var_dump($user);
        // var_dump($service);
        Cache::set('user', $user);
        Cache::set('service', $service);
        return;
    }
    
    public function onClose($fd, $reactorId)
    {
        return ;
    }
}